<?php
header('Content-Type: application/json; charset=utf-8');

// 数据库连接信息
$servername = "localhost"; //数据库地址
$username = "root";  //数据库用户名
$password = "";   //数据库密码
$dbname = "search_question_db";  //数据库名

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die(json_encode([
        "code" => 0,
        "data" => [
            "question" => "无",
            "answer" => "数据库连接失败"
        ],
        "message" => "请求失败"
    ]));
}

// 获取关键词
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';

if (empty($keyword)) {
    echo json_encode([
        "code" => 0,
        "data" => [
            "question" => "无",
            "answer" => "题目不能为空"
        ],
        "message" => "请求失败"
    ]);
    exit();
}

// 忽略符号和中英文标点符号
$keyword = preg_replace('/[^\w\s\u4e00-\u9fa5]/u', '', $keyword);

// 搜索框
$sql = "SELECT * FROM questions WHERE question LIKE '%$keyword%' LIMIT 1";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo json_encode([
        "code" => 1,
        "data" => [
            "question" => $row['question'],
            "answer" => $row['answer']
        ],
        "message" => "请求成功"
    ]);
} else {
    echo json_encode([
        "code" => 0,
        "data" => [
            "question" => $keyword,
            "answer" => "非常抱歉，题目搜索不到。"
        ],
        "message" => "请求失败"
    ]);
}

$conn->close();
?>